package com.ayz.gateway.client.connection;


import com.ayz.gateway.client.ServerInfo;
import com.ayz.gateway.client.exception.ExecuteRequestException;
import com.ayz.gateway.client.executor.GrpcRequestExecutor;
import com.ayz.gateway.client.executor.RequestExecutor;
import com.ayz.gateway.client.executor.RequestExecutorRegistry;
import com.ayz.gateway.client.executor.ResponseCallback;
import io.grpc.ManagedChannel;

import java.util.concurrent.TimeoutException;


/**
 * @ClassName GrpcConnection
 * @Description TODO: GRPC实现的客户端连接
 * @Author 快乐的星球
 * @Date 2023/5/20 17:03
 * @Version 1.0
 **/
public class GrpcConnection extends AbstractConnection{
    /**
     * 与远端的数据传输通道
     */
    private ManagedChannel managedChannel;


    public GrpcConnection(ManagedChannel managedChannel, ServerInfo serverInfo, RequestExecutorRegistry requestExecutorRegistry) {
        super(serverInfo, requestExecutorRegistry);
        this.managedChannel=managedChannel;
    }

    @Override
    public Object request(int requestCode, Object request, long timeoutMills) throws TimeoutException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        GrpcRequestExecutor grpcRequestExecutor=(GrpcRequestExecutor) requestExecutor;
        return grpcRequestExecutor.request(getManagedChannel(),request,timeoutMills);
    }

    @Override
    public void asyncRequest(int requestCode, Object request, ResponseCallback responseCallback) throws TimeoutException, ExecuteRequestException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        GrpcRequestExecutor grpcRequestExecutor=(GrpcRequestExecutor) requestExecutor;
        grpcRequestExecutor.asyncRequest(getManagedChannel(),request,responseCallback);
    }

    @Override
    public void requestOneway(int requestCode, Object request) throws ExecuteRequestException {
        RequestExecutor requestExecutor = getRequestExecutorRegistry().getRequestExecutor(requestCode);
        GrpcRequestExecutor grpcRequestExecutor=(GrpcRequestExecutor) requestExecutor;
        grpcRequestExecutor.requestOneway(managedChannel,request);
    }

    public ManagedChannel getManagedChannel() {
        return managedChannel;
    }
    public void setManagedChannel(ManagedChannel managedChannel) {
        this.managedChannel = managedChannel;
    }
    @Override
    public void close() {
        managedChannel.shutdown();
    }
}
